/**
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 */
package com.jeesite.modules.storage.web;

import com.jeesite.modules.storage.util.WebUtil;
import net.coobird.thumbnailator.Thumbnails;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.service.ResourceOwnerPasswordCredentialsGrant;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.UUID;

/**
 * 基础Controller
 */
public class BaseController extends com.jeesite.common.web.BaseController {

    public static final String OFFICE_EXCEL_XLS = "xls";
    public static final String OFFICE_EXCEL_XLSX = "xlsx";

    /*
     * 获取Workbook
     * */
    protected static Workbook getWorkbook(String filePath){
        File tempFile = new File(WebUtil.getResourcePath(filePath));
        FileInputStream fileInputStream;
        Workbook workBook = null;
        try {
            fileInputStream = new FileInputStream(tempFile);
            if(filePath.toLowerCase().endsWith(OFFICE_EXCEL_XLS)){
                workBook = new HSSFWorkbook(fileInputStream);
            }
            else if(filePath.toLowerCase().endsWith(OFFICE_EXCEL_XLSX)){
                workBook = new XSSFWorkbook(fileInputStream);
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
        return workBook;
    }

    /*
    * 获取Workbook
    * */
    protected static Workbook getWorkbook(MultipartFile file){
        String fileName = file.getOriginalFilename();
        File tempFile = new File(WebUtil.getUserFilesPath("/temp/import/" + UUID.randomUUID() + fileName.substring(fileName.lastIndexOf("."))));
        FileInputStream fileInputStream;
        Workbook workBook = null;
        try {
            WebUtil.checkFile(tempFile.getPath());
            file.transferTo(tempFile);
            fileInputStream = new FileInputStream(tempFile);
            if(file.getOriginalFilename().toLowerCase().endsWith(OFFICE_EXCEL_XLS)){
                workBook = new HSSFWorkbook(fileInputStream);
            }
            else if(file.getOriginalFilename().toLowerCase().endsWith(OFFICE_EXCEL_XLSX)){
                workBook = new XSSFWorkbook(fileInputStream);
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
        return workBook;
    }

    /*
     * 获取单元格值
     * */
    protected static String getCellValue(Row row,Integer cellNum){
        return getCellValue(row.getCell(cellNum));
    }

    /**
     * excel文件的数据读取,包括后缀为xls,xlsx
     * @param xssfRow
     * @return
     */
    @SuppressWarnings("deprecation")
    protected static String getCellValue(Cell cell) {
        if(cell==null){
            return "";
        }
        switch (cell.getCellType()) {
            case Cell.CELL_TYPE_STRING:
                return cell.getRichStringCellValue().getString();
            case Cell.CELL_TYPE_NUMERIC:
                // 判断是日期时间类型还是数值类型
                if (DateUtil.isCellDateFormatted(cell)) {
                    short format = cell.getCellStyle().getDataFormat();
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                    /* 所有日期格式都可以通过getDataFormat()值来判断
                     *     yyyy-MM-dd----- 14
                     *    yyyy年m月d日----- 31
                     *    yyyy年m月--------57
                     *    m月d日  --------- 58
                     *    HH:mm---------- 20
                     *    h时mm分  --------- 32
                     */
                    if(format == 14 || format == 31 || format == 57 || format == 58){
                        //日期
                        simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                    }else if (format == 20 || format == 32) {
                        //时间
                        simpleDateFormat = new SimpleDateFormat("HH:mm");
                    }
                    return simpleDateFormat.format(cell.getDateCellValue());
                } else {
                    // 对整数进行判断处理
                    double cur = cell.getNumericCellValue();
                    long longVal = Math.round(cur);
                    Object inputValue = null;
                    if(Double.parseDouble(longVal + ".0") == cur) {
                        inputValue = longVal;
                    }
                    else {
                        inputValue = cur;
                    }
                    return String.valueOf(inputValue);
                }
            case Cell.CELL_TYPE_BOOLEAN:
                return String.valueOf(cell.getBooleanCellValue());
            case Cell.CELL_TYPE_FORMULA:
                //对公式进行处理,返回公式计算后的值,使用cell.getCellFormula()只会返回公式
//                return String.valueOf(formulaEvaluator.evaluate(cell).getNumberValue());
            //Cell.CELL_TYPE_BLANK || Cell.CELL_TYPE_ERROR
            default:
                return "";
        }
    }

    /*
    * 获取行
    * */
    protected static Row getRow(Sheet sheet,Integer rowNum) {
        Row row = sheet.getRow(rowNum);
        return row == null ? sheet.createRow(rowNum) : row;
    }

    /*
     * 获取行
     * */
    protected static Cell getCell(Row row, Integer cellNum) {
        Cell cell =   row.getCell(cellNum);
        return cell == null ? row.createCell(cellNum) : cell;
    }

    /*
     * 获取行
     * */
    protected static Cell getCell(Sheet sheet,Integer rowNum, Integer cellNum) {
        return getCell(getRow(sheet,rowNum),cellNum);
    }

    /**
     * 下载导入数据模板
     */
    protected static void importTemplate( HttpServletResponse response , String templateName) {
        try {
            response.setHeader("Content-disposition", "attachment;fileName=" + URLEncoder.encode(templateName,"UTF-8"));
            response.setContentType("application/octet-stream; charset=utf-8");
            String filePath = WebUtil.getResourcePath("/template/" + templateName);
            WebUtil.checkFile(filePath);
            FileInputStream fileInputStream = new FileInputStream(filePath);
            OutputStream outputStream = response.getOutputStream();
            byte[] b = new byte[2048];
            int len;
            while ((len = fileInputStream.read(b)) != -1) {
                outputStream.write(b, 0, len);
            }
            fileInputStream.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * 导出数据
     */
    protected static void exportData( HttpServletResponse response , String name,Workbook workbook) {
        try {
            response.setHeader("Content-disposition", "attachment;fileName=" + URLEncoder.encode(name,"UTF-8"));
            response.setContentType("application/octet-stream; charset=utf-8");
            workbook.write(response.getOutputStream());
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}